#include <iostream>
#include <memory>
#include <string>
#include "epollServer.hpp"
#include "Log.hpp"
#include "Err.hpp"
#include "Protocol.hpp"

using namespace std;

void Usage(const char *proc)
{
    cout << "=============================" << endl;
    cout << "Usage:" << endl;
    cout << "\t" << proc << " port" << endl;
    cout << "=============================" << endl;
}

// 业务处理函数
ns_protocol::Response ServiceHandler(ns_protocol::Request &req)
{
    // 计算
    int result = 0;
    int code = 0;

    switch (req.getOP())
    {
    case '+':
        result = req.getX() + req.getY();
        break;
    case '-':
        result = req.getX() - req.getY();
        break;
    case '*':
        result = req.getX() * req.getY();
        break;
    case '/':
        if (req.getY() == 0)
            code = 1;
        else
            result = req.getX() / req.getY();
        break;
    case '%':
        if (req.getY() == 0)
            code = 2;
        else
            result = req.getX() % req.getY();
        break;
    default:
        code = 3; // 未知运算符
        break;
    }

    return ns_protocol::Response(result, code);
}

int main(int argc, char *args[])
{
    if (argc != 2)
    {
        Usage(args[0]);
        logMessage(Warning, "Parameters are not used correctly");
        exit(USER_ERR);
    }

    uint16_t port = stoi(args[1]);
    shared_ptr<Yohifo::EpollServer> psvr(new Yohifo::EpollServer(ServiceHandler, port));
    psvr->InitServer();
    psvr->Dispatcher();

    return 0;
}